package com.fy.common.handler;

import com.fy.common.enums.ErrorType;
import com.fy.common.model.ResponseResult;
import com.fy.common.spring.LocaleMessageSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionAdvice {
    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class);
    @Autowired
    private LocaleMessageSource localeMessageSource;
    @Autowired
    private MessageSource messageSource;
    /**
     * 处理@Valid校验异常
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult argumentNotValidExceptionExceptionHandler(MethodArgumentNotValidException ex){
        StringBuffer sb = new StringBuffer();
        BindingResult bindingResult = ex.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if (fieldErrors != null && !fieldErrors.isEmpty()) {
            for (FieldError fieldError : fieldErrors) {
                String message = localeMessageSource.getMessage(fieldError.getDefaultMessage()
                        .replace("{", "")
                        .replace("}", ""));
                if (sb != null && sb.length() == 0) {
                    sb.append(message);
                }
                logger.error("error request object=" + fieldError.getObjectName() + ", error field=" + fieldError.getField() + ", value=" + fieldError.getRejectedValue() +
                        ", default message =" + message);
            }
        }
        return ResponseResult.fail(ErrorType.SYSTEM_ERROR.getErrorKey(), sb.toString());
    }

    /***
     **异常处理
     ***/
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public ResponseResult<?> ExceptionHandler(Exception exceededException, HttpServletRequest request, HttpServletResponse response) {
        if (exceededException != null && exceededException instanceof MaxUploadSizeExceededException) {
            System.out.println("文件超长");
            return ResponseResult.fail(ErrorType.UPLOAD_FILE_SIZE_EXCEEDED_ERROR.getErrorKey(), "error.upload.file.size.exceeded");
        } else {
            return ResponseResult.fail();
        }
    }
}
